//
//  ViewD.m
//  drag
//
//  Created by 梁羽 on 2025/6/29.
//

#import "ViewD.h"

@implementation ViewD

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor clearColor];
        self.lineColor = [UIColor blueColor];
        self.lineWidth = 2.0;
        
        // 初始化直线端点（对角线）
        _startPoint = CGPointMake(20, 20);
        _endPoint = CGPointMake(frame.size.width - 20, frame.size.height - 20);
        
        // 添加端点按钮
        [self setupEndpointButtons];
        
        // 添加拖动手势
        UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
        [self addGestureRecognizer:panGesture];
    }
    return self;
}

- (void)setupEndpointButtons {
    NSMutableArray *buttons = [NSMutableArray array];
    
    for (NSInteger i = 0; i < 2; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(0, 0, 30, 30);
        button.backgroundColor = [UIColor orangeColor];
        button.layer.cornerRadius = 15;
        button.layer.borderWidth = 1;
        button.layer.borderColor = [UIColor blackColor].CGColor;
        button.tag = i; // 0:起点 1:终点
        
        UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handleEndpointPan:)];
        [button addGestureRecognizer:panGesture];
        
        [buttons addObject:button];
        [self addSubview:button];
    }
    
    self.endpointButtons = [buttons copy];
    [self updateEndpointPositions];
}

- (void)updateEndpointPositions {
    // 更新端点按钮位置
    self.endpointButtons[0].center = self.startPoint;
    self.endpointButtons[1].center = self.endPoint;
}

- (void)drawRect:(CGRect)rect {
    [super drawRect:rect];
    
    // 绘制直线
    UIBezierPath *linePath = [UIBezierPath bezierPath];
    [linePath moveToPoint:self.startPoint];
    [linePath addLineToPoint:self.endPoint];
    
    [self.lineColor setStroke];
    linePath.lineWidth = self.lineWidth;
    [linePath stroke];
}

- (void)handlePan:(UIPanGestureRecognizer *)gesture {
    if (gesture.state == UIGestureRecognizerStateBegan) {
        // 记录初始位置
        _panStartLocation = [gesture locationInView:self.superview];
    }
    else if (gesture.state == UIGestureRecognizerStateChanged) {
        CGPoint currentLocation = [gesture locationInView:self.superview];
        CGPoint translation = CGPointMake(currentLocation.x - _panStartLocation.x,
                                         currentLocation.y - _panStartLocation.y);
        
        CGPoint newCenter = CGPointMake(self.center.x + translation.x,
                                       self.center.y + translation.y);
        
        // 限制不超出容器边界
        CGFloat minX = self.frame.size.width / 2;
        CGFloat maxX = self.superview.frame.size.width - self.frame.size.width / 2;
        CGFloat minY = self.frame.size.height / 2;
        CGFloat maxY = self.superview.frame.size.height - self.frame.size.height / 2;
        
        newCenter.x = MAX(minX, MIN(newCenter.x, maxX));
        newCenter.y = MAX(minY, MIN(newCenter.y, maxY));
        
        self.center = newCenter;
        _panStartLocation = currentLocation;
    }
    else if (gesture.state == UIGestureRecognizerStateEnded ||
              gesture.state == UIGestureRecognizerStateCancelled) {
         [self notifyLinePathUpdate];
     }
}

- (void)handleEndpointPan:(UIPanGestureRecognizer *)gesture {
    UIButton *button = (UIButton *)gesture.view;
    if (gesture.state == UIGestureRecognizerStateChanged) {
        CGPoint translation = [gesture translationInView:self];
        
        // 更新端点位置
        if (button.tag == 0) {
            // 起点
            self.startPoint = CGPointMake(self.startPoint.x + translation.x,
                                        self.startPoint.y + translation.y);
        } else {
            // 终点
            self.endPoint = CGPointMake(self.endPoint.x + translation.x,
                                      self.endPoint.y + translation.y);
        }
        
        [gesture setTranslation:CGPointZero inView:self];
        [self updateEndpointPositions];
        [self setNeedsDisplay];
        
        // 调整视图大小以适应端点
        [self adjustViewSizeToFitEndpoints];
    }
    else if (gesture.state == UIGestureRecognizerStateEnded ||
             gesture.state == UIGestureRecognizerStateCancelled) {
        [self notifyLinePathUpdate];
    }
}

- (void)adjustViewSizeToFitEndpoints {
    // 计算包含两个端点的最小矩形（在self的坐标系中）
    CGFloat minX = MIN(self.startPoint.x, self.endPoint.x);
    CGFloat maxX = MAX(self.startPoint.x, self.endPoint.x);
    CGFloat minY = MIN(self.startPoint.y, self.endPoint.y);
    CGFloat maxY = MAX(self.startPoint.y, self.endPoint.y);
    
    // 添加边距
    CGFloat margin = 30;
    CGFloat requiredWidth = maxX - minX + margin * 2;
    CGFloat requiredHeight = maxY - minY + margin * 2;
    
    // 计算新frame的原点（在父视图坐标系中）
    CGPoint newOriginInSuperview = CGPointMake(
        self.frame.origin.x + minX - margin,
        self.frame.origin.y + minY - margin
    );
    
    // 确保新frame不会超出父视图边界
    newOriginInSuperview.x = MAX(0, newOriginInSuperview.x);
    newOriginInSuperview.y = MAX(0, newOriginInSuperview.y);
    
    // 计算最大允许尺寸
    CGFloat maxAllowedWidth = self.superview.bounds.size.width - newOriginInSuperview.x;
    CGFloat maxAllowedHeight = self.superview.bounds.size.height - newOriginInSuperview.y;
    
    requiredWidth = MIN(requiredWidth, maxAllowedWidth);
    requiredHeight = MIN(requiredHeight, maxAllowedHeight);
    
    // 确保视图不会小于最小尺寸
    requiredWidth = MAX(requiredWidth, 60);
    requiredHeight = MAX(requiredHeight, 60);
    
    // 计算新frame
    CGRect newFrame = CGRectMake(
        newOriginInSuperview.x,
        newOriginInSuperview.y,
        requiredWidth,
        requiredHeight
    );
    
    // 调整端点坐标到新坐标系
    CGPoint newStartPoint = CGPointMake(
        self.startPoint.x - minX + margin,
        self.startPoint.y - minY + margin
    );
    CGPoint newEndPoint = CGPointMake(
        self.endPoint.x - minX + margin,
        self.endPoint.y - minY + margin
    );
    
    // 应用变化
    self.frame = newFrame;
    self.startPoint = newStartPoint;
    self.endPoint = newEndPoint;
    [self updateEndpointPositions];
    [self setNeedsDisplay];
}

- (void)notifyLinePathUpdate {
    // 通知外部直线路径已更新
    //UIBezierPath *ellipsePath = [self linePathInPDFCoordinates];
    //[[NSNotificationCenter defaultCenter] postNotificationName:@"8888-9999" object:nil userInfo:@{@"path": NSStringFromCGRect([self getlineRect]), @"type": @"3"}];
    
    NSDictionary *lineInfo = @{
            @"startPoint": [NSValue valueWithCGPoint:[self lineStartPointInSuperview]],
            @"endPoint": [NSValue valueWithCGPoint:[self lineEndPointInSuperview]],
            @"type": @"3"
        };
    [[NSNotificationCenter defaultCenter] postNotificationName:@"8888-9999" object:nil userInfo:lineInfo];
}

- (CGRect)getlineRect {
    CGRect bounds = CGRectMake(self.startPoint.x,
                               self.startPoint.y,
                               self.endPoint.x - self.startPoint.x,
                               self.endPoint.y - self.startPoint.y);
    CGRect rect = [self convertRect:bounds toView:self.superview];
    return rect;
}

- (CGPoint)lineStartPointInSuperview {
    return [self convertPoint:self.startPoint toView:self.superview];
}

- (CGPoint)lineEndPointInSuperview {
    return [self convertPoint:self.endPoint toView:self.superview];
}

@end
